#include "led.h"
#include "globalDevice.h"
#include "gd32f4xx_gpio.h"
#include "gd32f4xx_rcu.h"

// 外设引脚和端口数组
device_pin_t device_pin[DEVICE_PIN_MAX] = {0};

void device_pin_init(void)
{
    /* 使能所有 LED GPIO 时钟 */
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_GPIOB);
    rcu_periph_clock_enable(RCU_GPIOC);
    rcu_periph_clock_enable(RCU_GPIOD);
    rcu_periph_clock_enable(RCU_GPIOE);
    rcu_periph_clock_enable(RCU_GPIOF);
    rcu_periph_clock_enable(RCU_GPIOG);
    device_pin[LED1].port = LED1_GPIO_PORT;
    device_pin[LED1].pin = LED1_PIN;
    device_pin[LED1].mode = DEVICE_MODE_OUTPUT;
    device_pin[LED1].invert = 0;
    device_pin[LED2].port = LED2_GPIO_PORT;
    device_pin[LED2].pin = LED2_PIN;
    device_pin[LED2].mode = DEVICE_MODE_OUTPUT;
    device_pin[LED2].invert = 0;
    device_pin[LED3].port = LED3_GPIO_PORT;
    device_pin[LED3].pin = LED3_PIN;    
    device_pin[LED4].port = LED4_GPIO_PORT;
    device_pin[LED4].pin = LED4_PIN;
    device_pin[LED4].mode = DEVICE_MODE_OUTPUT;
    device_pin[LED4].invert = 0;
    
    for (device_enum_t i = 0; i < DEVICE_PIN_MAX; i++)
    {
        switch (device_pin[i].mode)
        {
        case DEVICE_MODE_OUTPUT:
            gpio_mode_set(device_pin[i].port, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, device_pin[i].pin);
            gpio_output_options_set(device_pin[i].port, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, device_pin[i].pin);
            break;
        case DEVICE_MODE_OUTPUT_PULLUP:
            gpio_mode_set(device_pin[i].port, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP, device_pin[i].pin);
            gpio_output_options_set(device_pin[i].port, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, device_pin[i].pin);
            break;
        case DEVICE_MODE_OUTPUT_PULLDOWN:
            gpio_mode_set(device_pin[i].port, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLDOWN, device_pin[i].pin);
            gpio_output_options_set(device_pin[i].port, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, device_pin[i].pin);
            break;
        case DEVICE_MODE_INPUT:
            gpio_mode_set(device_pin[i].port, GPIO_MODE_INPUT, GPIO_PUPD_NONE, device_pin[i].pin);
            break;
        case DEVICE_MODE_INPUT_PULLUP:
            gpio_mode_set(device_pin[i].port, GPIO_MODE_INPUT, GPIO_PUPD_PULLUP, device_pin[i].pin);
            break;
        case DEVICE_MODE_INPUT_PULLDOWN:
            gpio_mode_set(device_pin[i].port, GPIO_MODE_INPUT, GPIO_PUPD_PULLDOWN, device_pin[i].pin);
            break;
        default:
            break;
        }
    }
}
